import datetime

# 计算BMR
def calculate_bmr(weight, height, age, gender):
    if gender == "男":
        bmr = 66 + (13.7 * weight) + (5 * height) - (6.8 * age)
    elif gender == "女":
        bmr = 655 + (9.6 * weight) + (1.8 * height) - (4.7 * age)
    else:
        bmr = None
    return bmr

# 评定 BMR
def rate_bmr(bmr):
    if bmr < 1200:
        return "偏低，请注意身体健康！"
    elif bmr < 2000:
        return "健康，请继续保持！"
    else:
        return "偏高，请注意饮食健康！"

# 显示历史记录
def show_history():
    try:
        with open("user_data.txt", "r") as f:
            content = f.read()
            print(content if content else "暂无历史数据")
    except FileNotFoundError:
        print('暂无历史数据')

# 删除历史记录
def delete_history():
    try:
        print("请选择删除记录的方式:\n1. 删除所有记录\n2. 删除指定日期的记录\n3. 按BMR值删除记录")
        option = input("请选择功能序号：")
        if option == "1":
            with open("user_data.txt", "w") as f:
                f.write("")
            print("已删除所有记录")
        elif option == "2":
            date = input("请输入要删除的日期（格式：YYYY-MM-DD）：")
            with open("user_data.txt", "r") as f:
                lines = f.readlines()
            with open("user_data.txt", "w") as f:
                for line in lines:
                    if not line.startswith(date):
                        f.write(line)
                print("已删除指定日期的记录")
        elif option == "3":
            bmr = float(input("请输入要删除的BMR值："))
            with open("user_data.txt", "r") as f:
                lines = f.readlines()
            with open("user_data.txt", "w") as f:
                for line in lines:
                    components = line.strip().split(" ")
                    if len(components) >= 7 and float(components[6].split("：")[1][:-3]) != bmr:
                        f.write(line)
                print("已删除指定BMR值的记录")
        else:
            print("输入有误，请重新选择功能！")
    except FileNotFoundError:
        print("暂无历史记录，无法删除。")

# 主程序
while True:
    try:
        print("请选择功能：\n1. 计算基础代谢率\n2. 查看历史基础代谢率记录\n3. 删除历史记录")
        option = input("请选择功能序号：")
        if option == "1":
            weight = float(input("请输入您的体重（单位：千克）："))
            height = float(input("请输入您的身高（单位：厘米）："))
            age = int(input("请输入您的年龄："))
            gender = input("请输入您的性别（男/女）：")
            now = datetime.datetime.now()
            bmr = calculate_bmr(weight, height, age, gender)
            if bmr is None:
                print("输入性别有误！")
            else:
                msg = rate_bmr(bmr)
                print("您的基础代谢率是：%.2f 千卡/天，" % bmr + msg)
                with open("user_data.txt", "a") as f:
                    f.write(f"\n{now.strftime('%Y-%m-%d %H:%M:%S')} 体重：{weight}kg，身高：{height}cm，年龄：{age}岁，性别：{gender}，BMR：{bmr:.2f}千卡/天，评级：{msg}")

        elif option == "2":
            show_history()

        elif option == "3":
            delete_history()

        else:
            print("输入有误，请重新选择功能！")

    except ValueError:
        print("输入数据有误，请重新输入！")

    else:
        repeat = input("是否继续（Y/N）？")
        if repeat.lower() != "y":
            break